package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.InjectView;
import dmax.dialog.SpotsDialog;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.manager.AppConfig;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.MyfeedsDate;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.ClearEditText;
import project.dade.cn.bst.views.EmptyLayout;

public class RegPhoneVerActivity extends ZJPBaseBarActivity implements View.OnClickListener {

    private static String TAG = RegPhoneVerActivity.class.getSimpleName();
    @InjectView(R.id.identifyPhoneTv)
    TextView identifyPhoneTv; //手机号
    @InjectView(R.id.identifyCodeTimeTv)
    TextView identifyCodeTimeTv;//限制时间
    @InjectView(R.id.submitBtn)
    AppCompatButton submitBtn;//提交注册
    @InjectView(R.id.identifyEt)
    ClearEditText identifyEt;//验证码
    @InjectView(R.id.sendVerBtn)
    AppCompatButton sendVerBtn; //发送验证码
    private String account; //账号
    private String pass;//密码
    private TimeCount mTimeCount;


    //计时重发
    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            sendVerBtn.setClickable(false);
            sendVerBtn.setEnabled(false);
            sendVerBtn.setTextColor(getResources().getColor(R.color.universal_white));
            identifyCodeTimeTv.setText(millisUntilFinished / 1000 + "");
        }

        @Override
        public void onFinish() {
            //sendVerBtn.setText("获取验证码");
            identifyCodeTimeTv.setText("60");
            sendVerBtn.setClickable(true);
            sendVerBtn.setEnabled(true);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_phone_ver);
        initData();
        initSetListener();
    }


    private void initData() {
        pass = getIntent().getStringExtra("pass");
        account = getIntent().getStringExtra("account");
        identifyPhoneTv.setText(account);

    }

    private void initSetListener() {
        submitBtn.setOnClickListener(this);
        sendVerBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.sendVerBtn:
                AppUtil.closeSoftInput(this);
                if (AppUtil.isNetworkAvailable(RegPhoneVerActivity.this)) {
                    mTimeCount = new TimeCount(60000, 1000);
                    mTimeCount.start();
                    mSpDialog = new SpotsDialog(RegPhoneVerActivity.this);
                    mSpDialog.show();
                    requestSendVer();
                } else {
                    ToastUtil.showShort(RegPhoneVerActivity.this, R.string.tips_network_error);
                }


                break;
            case R.id.submitBtn:
                AppUtil.closeSoftInput(this);
                //数据验证
                if (isCheckInput()) {
                    if (AppUtil.isNetworkAvailable(RegPhoneVerActivity.this)) {
                        requestReg();
                    } else {
                        ToastUtil.showShort(RegPhoneVerActivity.this, R.string.tips_network_error);
                    }

                }
                break;

        }
    }


    /**
     * 发送验证码验证
     */

    private boolean isCheckInput() {
        //验证码不能为空
        if (TextUtils.isEmpty(identifyEt.getText().toString().trim())) {
            ToastUtil.showShort(this, R.string.tips_identifyCode_null);
            return false;
        }

        return true;
    }

    /**
     * 发送验证码请求
     */
    private void requestSendVer() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("MobilePhone", account);
        params.put("SmsType","0");
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.sendverifycode).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        mSpDialog.dismiss();
                        ToastUtil.showShort(RegPhoneVerActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        mSpDialog.dismiss();
                        LogUtil.i(TAG, "发送验证码：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "发送验证码"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "发送验证码：" + model.getData());
                        } else {
                            mSpDialog.dismiss();
                            ToastUtil.showShort(RegPhoneVerActivity.this, NetRequestUtil.requestsError(response, "发送验证码"));

                        }
                    }

                });
    }
    /**
     * 注册请求
     */
    private void requestReg() {
        HashMap<String,String > hashMap = new HashMap<String,String>();
        hashMap.put("MobilePhone",account);
        hashMap.put("PassWord",pass);
        hashMap.put("Code", identifyEt.getText().toString().trim());
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormEncodingBuilder()
                .add("MobilePhone", account)
                .add("PassWord", pass)
                .add("Code", identifyEt.getText().toString().trim())
                .add("Sign", FormatRequest.main(hashMap))
                .build();

        final Request request = new Request.Builder().url(ApiConfig.getHostAddress()+ ApiConfig.SERVER_URL.register)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Message msg = new Message();
                msg.what = 1;
                handle.sendMessage(msg);
                LogUtil.i(TAG, "注册异常：");

            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = response.body().string();
                    handle.sendMessage(msg);
                }
            }
        });


    }

    public Handler handle = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    mSpDialog.dismiss();
                    String json = (String) msg.obj;
                    LogUtil.i(TAG, "获取登录用户ID：" + json);
                    if (TextUtils.isEmpty(NetRequestUtil.requestsError(json, "登录"))) {
                        BaseRequestsModel model = JSON.parseObject(json, BaseRequestsModel.class);
                        //存储相关用户基础信息
                        LogUtil.i(TAG, "获取数据内容：" + json);
                        sendBroadcast(new Intent(AppConfig.ACTION_REG_SUCESS_FINISH));
                        RegPhoneVerActivity.this.finish();

                    } else {
                        ToastUtil.showShort(RegPhoneVerActivity.this, NetRequestUtil.requestsError(json, "登录"));

                    }
                    break;
                case 1:
                    ToastUtil.showShort(RegPhoneVerActivity.this, "网络相应失败请稍后再试");

            }
        }

        ;
    };
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
